package ltd.itlover.yqblog.application;

import android.util.Log;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import dagger.hilt.InstallIn;
import dagger.hilt.android.components.ApplicationComponent;
import ltd.itlover.yqblog.network.AccountApiService;
import ltd.itlover.yqblog.network.BlogApiService;
import ltd.itlover.yqblog.utils.TokenUtil;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

@InstallIn(ApplicationComponent.class)
@Module
public class NetworkModule {
    @Singleton
    @Provides
    OkHttpClient returnOkHttp() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("YQTAG", message);
            }

        }).setLevel(HttpLoggingInterceptor.Level.BODY);

//
        return new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                String token = null;
                Request originRequest = chain.request();
                token = TokenUtil.getToken();
                if(token != null){
                    Request newRequest = originRequest.newBuilder()
                            .header("Authorization", token)
                            .build();
                    return chain.proceed(newRequest);
                }
                return chain.proceed(originRequest);

            }
        })
                .connectTimeout(900, TimeUnit.MILLISECONDS)
                .addInterceptor(httpLoggingInterceptor).build();
    }

    @Singleton
    @Provides
    Retrofit provideRetrofit(OkHttpClient client) {
        return new Retrofit.Builder()
                .baseUrl("http://10.136.8.130")
                .client(client)
                //.addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    @Singleton
    @Provides
    BlogApiService provideBlogApiService(Retrofit retrofit) {
        return retrofit.create(BlogApiService.class);
    }

    @Singleton
    @Provides
    AccountApiService provideAccountApiService(Retrofit retrofit) {
        return retrofit.create(AccountApiService.class);
    }
}
